<template style="height: 100%;">
	<view class="page-container">
		<navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
		<view class="canvas-img">
			<image mode="aspectFit" v-if="canvasPath" :src="canvasPath" lazy-load="true">
			</image>
			<canvas canvas-id="canvas-ctx" ref="canvasRef" class="cas"
				:style="{ width: canvasW + 'px', height: canvasH + 'px', top: '2220rpx'}"></canvas>
		</view>
		<view class="footer-new" :class="[isIpx ? 'fix-iphonex-button' : '']">
			<button open-type="share">微信分享</button>
			<button class="save-img" @click='downImg' v-if="writePhotosAlbum">保存图片</button>
			<button class="save-img" @click='handleSetting' v-else>保存图片</button>
		</view>
	</view>
</template>

<script>
	import Painter from "@/utils/painter/index";
	import NavBar from '../../components/common/navbar';
	import tip from '@/utils/tip';
	import api from '@/api/api';
	import Util from '../../utils/filter.wxs'
	import {
		CUSTOMER_INFO
	} from '@/utils/constant';
	import {
		changeToObj
	} from '@/utils/commonActItems.js'
	export default {
		components: {
			navBar: NavBar,
		},
		data() {
			return {
				isShowCustomNavBar: true,
				postImage: '',
				navbarData: {
					showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
					navbarTitle: '分享' //导航栏 中间的标题
				},
				optionInfo: {},
				isIpx: false,
				canvasPath: '',
				screenWidth: '',
				screenHeight: '',
				posterMarginTop: '40rpx',
				logoUrl:'https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/pdp/logo.png',
				sunBaseCodeUrl: 'https://100000063-1252208446.cos.ap-shanghai.myqcloud.com/images/2022021422750.jpg',
				drawCodeUrl: 'https://100000063-1252208446.file.myqcloud.com/images/飞书20220512-195815.jpg',
				moenyIcon: 'https://100000063-1252208446.file.myqcloud.com/images/ICON/money.jpg',
				lineUrl: 'https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/pdp/line.png',
				canvasW: 310,
				canvasH: 550,
				memberCode: '',
				writePhotosAlbum: true

			}
		},
		onLoad: async function(options) {
			wx.showLoading({
				title: '海报生成中...',
			})

			let params = JSON.parse(decodeURIComponent(options.params))
			this.optionInfo = params

			await this.setfont()
			this.createPosterSunCode()
			let _this = this;
			let activitySwitch = params.activitySwitch
			wx.getSetting({
				complete: res => {
					if (res.authSetting['scope.writePhotosAlbum'] === false) {
						this.writePhotosAlbum = false
					}
				}
			})
		},
		onShow() {
			let systemInfo = uni.getSystemInfoSync();
			let isIpx = systemInfo.model.indexOf('iPhone X') !== -1 || systemInfo.model.indexOf('iPhone1') !== -1 ||
				systemInfo.model.indexOf('unknown<iPhone13') !== -1;
			this.isIpx = isIpx;
			getApp().cl_tracker.track('mini_program_view', {
				path: 'pages/item/itemShare',
				pageName: '分享海报',
			})
		},
		methods: {
		 async	setfont(){
			let a=	await wx.loadFontFace({
				          family: 'NotoSansSC-Medium',
				          source: 'url("https://100000063-1252208446.file.myqcloud.com/fonts/revamp/NotoSansSC-Medium.ttf")',
				          scopes: ['webview', 'native'],
				        })
			let b=	   await  wx.loadFontFace({
				          family: 'NotoSansSC-Regular',
				          source: 'url("https://100000063-1252208446.file.myqcloud.com/fonts/revamp/NotoSansSC-Regular.ttf")',
				          scopes: ['webview', 'native']
				        })
				let c=	   await  wx.loadFontFace({
				          family: 'FrankNew-Medium',
				          source: 'url("https://100000063-1252208446.file.myqcloud.com/fonts/revamp/FrankNew-Medium.otf")',
				          scopes: ['webview', 'native']
				        })
				   let d=	  await  wx.loadFontFace({
				          family: 'FrankNew-Regular',
				          source: 'url("https://100000063-1252208446.file.myqcloud.com/fonts/revamp/FrankNew-Regular.otf")',
				          scopes: ['webview', 'native']
				        })

						return null
			},
			handleSetting() {
				wx.showModal({
					title: '提示',
					content: '需要您授权保存相册',
					showCancel: false,
					success: modalSuccess => {
						wx.openSetting({
							success: res => {

								if (res.authSetting[
										'scope.writePhotosAlbum']) {
									wx.showModal({
										title: '提示',
										content: '获取权限成功，再次点击下载海报',
										showCancel: false
									})
									this.writePhotosAlbum = true
								} else {
									wx.showModal({
										title: '提示',
										content: '获取权限失败，将无法保存到相册',
										showCancel: false,
									})
								}
							},

						})
					}
				})
			},
			async showPoster(sunCodeUrl) {
				const getImages = [this.optionInfo.url, sunCodeUrl, this.moenyIcon,this.logoUrl,this.lineUrl].map((imgSrc) => {
					return new Promise(async (resolve) => {
						const r = await this.getImageInfo({
							imgSrc
						})
						resolve(r)
					})
				})
				const [mainPic, sunCodeImage, moneyPic,logoUrl,lineUrl] = await Promise.all(getImages)
				// conso.log("-------------------------------",lineUrl)
				const canvasWidth = 310;
				const canvasHeight = 550;
				const painter = new Painter("canvas-ctx", this.$refs.canvasRef, {
					width: canvasWidth,
					height: canvasHeight,
				});

				// 海报底色(纯白)
				await painter.drawBlock({
					x: 0,
					y: 0,
					width: canvasWidth,
					height: canvasHeight,
					bgColor: "#fff",
				});
				await painter.drawBlock({
					x: 0,
					y: 0,
					width: 310,
					height: 314,
					bgColor: "#FAFAFA",
				});



				// 主图
				await painter.drawImage({
					x: 20,
					y: 43,
					width: 270,
					height: 270,
					image: mainPic.path,
				});
				// logo
				await painter.drawImage({
					x: 91,
					y: 20,
					width: 128,
					height: 28,
					image: logoUrl.path,
				});

				// 标题
				const itemName = this.optionInfo.itemName;
				let tArr = itemName.split('\n')

				// let t = itemName.replace("12","\n")
				const textLeftSpace = 24
				const titleWidth = 264;
				let iconY, iconX, suncodeY;
				await painter.drawMultipleLine(({
					y,
					height
				}) => {

					return {
						text: tArr[0],
						align: "left",
						lineHeight:   20,
						maxWidth: titleWidth,
						size: 14,
						x: textLeftSpace,
						y: 340,
						line:  tArr[1]?1:2,
						fontWeight: 500,
						fontF:'NotoSansSC-Medium',
						color: "#000"
					};
				});
				await painter.drawMultipleLine(({
					y,
					height
				}) => {
					return {
						text: tArr[1] ||'',
						align: "left",
						lineHeight: 20,
						maxWidth: titleWidth,
						size: 14,
						x: textLeftSpace,
						y: y + height ,
						line: 1,
						fontWeight: 500,
						fontF:'NotoSansSC-Medium',
						color: "#000000"
					};
				});
				// ￥符号

				// // 货币符号
				// await painter.drawText(({
				//   y,
				//   height
				// }) => {
				//   iconY = y + height + 10
				//   iconX = 20
				//   return {
				//     // // text: '¥',
				//     // size: 13,
				//     // lineHeight: 15,
				//     // x: textLeftSpace,
				//     // y: y + height + 10,
				//     // // fontWeight: 'bold'
				//   }
				// });

				// await painter.drawImage({
				// 	x: 24,
				// 	y: 392,
				// 	width: 10,
				// 	height: 12,
				// 	image: moneyPic.path,
				// });
				// 价格
				await painter.drawText(({
					y,
					width
				}) => {
					return {
						text: '￥'+ Util.moneyFormat(this.optionInfo.price, 2),
						size: 12,
							x: 24,
							y: 392,
						fontWeight: 400,
						fontF:'FrankNew-Regular',
						color: '#000000',
					}
				});
				//-------------
				await painter.drawImage({
					x: textLeftSpace,
					y: 427,
					width: 262,
					height: 6,
					image: lineUrl.path,
				});

				const textConfig = {
					size: 10,
					x: textLeftSpace,
					color: '#757575',
						lineHeight: 16,
				}

				await painter.drawText(({
					y,
					height
				}) => {
					// suncodeY = y + height + 20
					return {
						text: 'THE MACALLAN麦卡伦线上精品店',
						lineHeight: 20,
						y: 462,
						size: 12,
						color: '#000000',
						x: textLeftSpace,
						fontWeight:400,
						 fontF:"NotoSansSC-Regular"
					}
				});
				// 文案
				await painter.drawText(({
					y,
					height
				}) => {

					return {
						text: '长按识别二维码',
						y: y + height + 12,
						...textConfig,
					}
				});

				await painter.drawText(({
					y,
					height
				}) => {
					return {
						text: '即刻选购',
						y: y + height ,
						...textConfig,
					}
				});



				// 太阳码
				await painter.drawImage({
					x: 223,
					y: 462,
					width: 64,
					height: 64,
					imageWidth: sunCodeImage.width,
					imageHeight: sunCodeImage.height,
					image: sunCodeImage.path,
				});


				const img = await painter.getImage();
				this.canvasPath = img;
				wx.hideLoading();
			},

			//二维码或太阳
			async getImageInfo({imgSrc}) {
				let _this = this;
				return new Promise((resolve, errs) => {
					uni.getImageInfo({
						src: imgSrc,
						success: function(image) {
							resolve(image);
						},
						fail(err) {
							errs(err);
							wx.hideLoading();
							tip.plainText('海报生成失败');
						}
					}, this);
				});
			},
			// 动态生成太阳码
			createPosterSunCode: async function() {
				const that = this;
				let scene = await this.setScence()
				let sharePosterPath = this.optionInfo.sharePosterPath
				let page;
				if (sharePosterPath?.indexOf('?') > 0) {
					page = sharePosterPath.substring(0, sharePosterPath.indexOf('?'))
				} else {
					page = sharePosterPath
				}

				let merchantInfo = uni.getStorageSync('merchantInfo');
				let customerInfo = uni.getStorageSync('customerInfo');
				const result = await api.createSunCode({
					header: {
						jwt: customerInfo.jwt
					},
					method: 'POST',
					query: {
						appId: uni.getAccountInfoSync().miniProgram.appId,
						scene: scene,
						page:page,
						envVersion: api.environment == 'trial' ? 'trial' : 'release',
						outputType: 'file-url'
					}
				});
				if (result.code == 1000) {

					this.showPoster(result.data)
				}
			},

			// 设置自定义海报参数
			setScence: async function() {
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || '';
				let query, values;
				let sharePosterPath = this.optionInfo.sharePosterPath
				if (sharePosterPath?.indexOf('?') > 0) {
					query = sharePosterPath.substring(sharePosterPath?.indexOf('?') + 1, sharePosterPath.length)
					values = changeToObj(query)
				}
				const sence = await api.setScence({
					method: 'POST',
					query: {
						key: 'sunCode' + '_' + this.optionInfo.goodsId + '_' + this.optionInfo.valueId,
						value: JSON.stringify(values)
					},
				})

				if (sence.code === 1000) {

					return sence.data.key
				}
			},
			downImg() {
				//保存海报图分享
				wx.saveImageToPhotosAlbum({
					filePath: this.canvasPath,
					success: result => {
						wx.showToast({
							title: '海报已保存，快去分享给好友吧。',
							icon: 'none'
						});
						this.finishTask()
					},
					fail: err => {

						wx.hideLoading()


					},
				});
			},
			onShareAppMessage: function(res) {
				this.finishTask()
				if (res.from === 'button') {
					// 来自页面内转发按钮

				} else {
					this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
				}
				const goodsPath = this.optionInfo.shareCardLink || '/pages/item/item?id=' + this.optionInfo.goodsId +
					'&valueId=' + this.optionInfo.valueId +
					'&valueName=' + this.optionInfo.colorName;
				this.$commonSensors.sensorsPageShare()
				return this.$commonFunction.commonShare(res, this.optionInfo.shareText, goodsPath, this.optionInfo
					.shareCardPicUrl);
			},
			// 完成任务
			finishTask() {
				if (!this.optionInfo.taskCenterCode) {
					return false
				}
				this.posterTrack("微信分享");
				let {
					taskCenterCode,
					taskContentId,
					taskContentName
				} = this.optionInfo
				getApp().finishTask(taskCenterCode, taskContentId, taskContentName, 0)
				setTimeout(() => {
					uni.navigateBack({
						delta: 3
					})
				}, 3000);
			},

			posterTrack(c_area) {
				const goodsPath = this.optionInfo.shareCardLink || '/pages/item/item?id=' + this.optionInfo.goodsId +
					'&valueId=' + this.optionInfo.valueId +
					'&valueName=' + this.optionInfo.colorName;
				let name = this.optionInfo.itemName;
				let posterShareParams = {
					"c_area": c_area,
					"c_link_pagename": name,
					"c_link_path": goodsPath
				}
				getApp().commonClTrack("c_ebmp_drawstask_product_poster_share", posterShareParams);
			},
		}
	}
</script>

<style lang="scss">
	.canvas-img {
		position: relative;
		margin: auto;
		display: flex;
		justify-content: center;

		&.fix-iphonex-button {
			margin: 100rpx auto 0;
		}

		.cas {
			background: #fff;
			position: fixed;
			top: -2000rpx;
		}

		image {
			width: 620rpx;
			height: 1100rpx;
		}
	}

	.footer-new {
		// &.fix-iphonex-button {
		// 	height: 120rpx;

		// 	button {
		// 		line-height: 120rpx;
		// 	}

		// 	.save-img {
		// 		line-height: 120rpx;
		// 	}
		// }

		position: fixed;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 32rpx 48rpx 64rpx;
		align-items: center;
		z-index: 9999;
		background-color: #fff;

		button {
			margin: 0;
			width: 320rpx;
			height: 80rpx;
			display: block;
			line-height: 76rpx;
			// background-color: #000;
			font-size: 28rpx;
			box-sizing: border-box;
			border: 2px solid #000000;
			color: #000000 !important;
			background-color: #fff !important;
			padding: 0 !important;
			border-radius: 48rpx 16rpx 48rpx 48rpx;

		}

		// .save-img {
		// 	font-size: 30rpx;
		// 	text-align: center;
		// 	width: 320rpx;
		// 	height: 100%;
		// 	line-height: 100rpx;
		// 	color: #fff;
		// 	background-color: #CB171A;
		// }
	}

	.page-container {
		display: flex;
		justify-content: center;
		background: #ECECEC;
		align-items: center;
		height: 100vh;
	}
</style>
